package com.slt.developkitweb.util.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


@Component
@Slf4j
public class AESUtils {
    @Value("${security.aesKey:F49E8CAC66C376FC}")
    private String key;

    public static String KEY;

    public static String encrypt(Object plaintext, String encryptMode) {
        String PlainText = null;
        try {
            PlainText = plaintext.toString();
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + encryptMode + "/PKCS5Padding");
            if (encryptMode.equals("ECB")) {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            } else {
                IvParameterSpec iv = new IvParameterSpec(KEY.getBytes("utf-8"));//使用CBC模式，需要一个向量iv，可增加加密算法的强度
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted = cipher.doFinal(PlainText.getBytes("utf-8"));
            return new String(new BASE64Encoder().encode(encrypted));
        } catch (Exception e) {
            log.error("aes encrypt error:", e);
            return null;
        }
    }

    /**
     * AES解密
     *
     * @param cipertex    密文
     * @param EncryptMode AES加密模式，CBC或ECB
     * @return 该密文的明文
     */
    public static String decrypt(Object cipertext, String EncryptMode) {
        String CipherText = null;
        try {
            CipherText = cipertext.toString();
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + EncryptMode + "/PKCS5Padding");
            if (EncryptMode.equals("ECB")) {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            } else {
                IvParameterSpec iv = new IvParameterSpec(KEY.getBytes("utf-8"));//使用CBC模式，需要一个向量iv，可增加加密算法的强度
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(CipherText);//先用base64解密

            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception e) {
            log.error("aes decrypt error:", e);
            return null;
        }
    }
    @PostConstruct
    public void key() {
        KEY = this.key;
    }
}
